import { useState, useEffect } from 'react';
import clsx from 'clsx';
import styles from './index.module.less';
import logoImg from '../../../assets/logo.png';
import menuImg from '../../../assets/menu.png';

const menuList = [
  { key: 'home', label: 'Home' },
  { key: 'system', label: 'iReadyGo System' },
  { key: 'iot', label: 'IoT Hardware' },
  { key: 'partner', label: 'Partner' },
  { key: 'about', label: 'About' },
  { key: 'contact', label: 'Contact' },
];

const Nav = () => {
  const [current, setCurrent] = useState('home');
  const [drawerOpen, setDrawerOpen] = useState(false);

  // 处理滚动锁定
  useEffect(() => {
    const root = document.querySelector('#root') as HTMLElement;
    if (drawerOpen) {
      root.style.overflow = 'hidden';
    } else {
      root.style.overflow = '';
    }
    // 清理函数
    return () => {
      root.style.overflow = '';
    };
  }, [drawerOpen]);

  const handlerChange = (nav: string) => {
    const anchorElement = document.getElementById(nav);
    if (anchorElement) {
      window.scrollTo({
        top: anchorElement.offsetTop,
        behavior: 'smooth',
      });
    }
    setCurrent(nav);
    setDrawerOpen(false);
  };

  const toggleDrawer = (open: boolean) => {
    setDrawerOpen(open);
  };

  return (
    <nav className={styles.nav}>
      <img className={styles.logo} src={logoImg} />
      <div className={styles.menu}>
        {menuList.map((item) => (
          <div
            key={item.key}
            className={clsx(styles.item, current === item.key && styles.active)}
            onClick={() => handlerChange(item.key)}
          >
            {item.label}
            <div className={styles.active_bar}></div>
          </div>
        ))}
      </div>
      <button className={styles.menuIcon} aria-label="menu" onClick={() => toggleDrawer(true)}>
        <img src={menuImg} alt="menu" style={{ width: 32, height: 32 }} />
      </button>
      {/* Drawer */}
      {drawerOpen && (
        <>
          <div className={styles.drawerMask} onClick={() => toggleDrawer(false)} />
          <div className={styles.drawer}>
            {menuList.map((item) => (
              <div
                key={item.key}
                className={clsx(styles.drawerItem, current === item.key && styles.drawerActive)}
                onClick={() => handlerChange(item.key)}
              >
                {item.label}
              </div>
            ))}
          </div>
        </>
      )}
    </nav>
  );
};

export default Nav;
